package cn.lkp.service.Impl;

import cn.lkp.service.FileService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;

@Service
public class FileServiceImpl implements FileService {
    @Override
    public String fileUpload(MultipartFile file, String path) throws IOException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSS");
        String res = sdf.format(new Date());
        if (file==null)
            return "fail";
        String originalFilename = file.getOriginalFilename();
        //获取文件后缀名
        String houzhui=originalFilename.substring(originalFilename.lastIndexOf(".")+1);

        if (!file.isEmpty()) {
            File dir = new File("D:/upload",res+"."+houzhui);
            if(!dir.exists()){
                dir.mkdirs();
            }
            file.transferTo(dir);
            return dir.getAbsolutePath();
        } else {
            return "fail";
        }
    }

    @Override
    public void fileDownload(HttpServletRequest request, HttpServletResponse response, String filePath) {
        ServletOutputStream out;
        //得到要下载的文件
        File file = new File(filePath);
        try {
            //设置响应头，控制浏览器下载该文件
            response.setContentType("multipart/form-data");
            //获得浏览器信息,并处理文件名
            String headerType=request.getHeader("User-Agent").toUpperCase();
            String fileName = null;
            if (headerType.indexOf("EDGE") > 0||headerType.indexOf("MSIE")>0||headerType.indexOf("GECKO")>0) {
                fileName=URLEncoder.encode(file.getName(), "UTF-8");
            }else{
                fileName= new String(file.getName().replaceAll(" ", "").getBytes("utf-8"), "iso8859-1");
            }
            response.addHeader("Content-Disposition", "attachment;filename="+fileName);
            response.addHeader("Content-Length", "" + file.length());
            FileInputStream inputStream = new FileInputStream(file);

            out = response.getOutputStream();

            int b = 0;
            byte[] buffer = new byte[1024];
            while (b != -1) {
                b = inputStream.read(buffer);
                //写到输出流(out)中
                if(b!=-1)
                    out.write(buffer, 0, b);
            }
            inputStream.close();
            out.close();//关闭输出流
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }
}
